Home:ALL Converter>Many "getContext()" or one private context = getContext() and use it?

Many "getContext()" or one private context = getContext() and use it?

Ask Time:2017-10-11T00:50:14         Author:Serg

Json Formatter

I need context many times in my fragment:

    ...
    account.restore(getContext());
    ...
    dbHelper = new DBHelper(getContext());
    ...
    DiskLruBasedCache.ImageCacheParams cacheParams = new DiskLruBasedCache.ImageCacheParams(getContext(), "CacheDirectory");
    ...
    mImageLoader = new SimpleImageLoader(getContext(), cacheParams);
    ...
    Toast.makeText(getContext(), "err: " + error, Toast.LENGTH_LONG).show();
    ...
    RecyclerView.LayoutManager layoutManager = new CustomLayoutManager(getContext());
    ...

Or should I initialize it once and then use it.

What is best way ?

Author:Serg,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/46671950/many-getcontext-or-one-private-context-getcontext-and-use-it
Petter Hesselberg :

This is mostly a matter of preference. You can call getContext() wherever you need one -- no cause to be worried about perf overhead. Or you can assign a private Context context field in your onCreate method. Or, if a particular method has multiple uses, create a local variable.\n\nIf getContext was potentially slow, then you should definitely have stashed it, but it's really just a simple accessor (almost -- it does one bit of indirection internally).\n\nGo with whatever you find most readable.",
2017-10-10T17:23:25
yy